<?php

const remote_host = '8.220.137.228';
const remote_user = 'sharewifi1';
const remote_password = '6RLHEAipBs3H2ajY';
const remote_dbname   = 'sharewifi1';
const remote_port     =  3306;

const api_remote_host = 'https://test.sharewifi.cc';
const frontend_root_domain = 'https://test.sharewifi.cc';

add_action( 'template_redirect', 'misha_add_to_cart_on_custom_page_and_redirect');
function misha_add_to_cart_on_custom_page_and_redirect(){
    if( is_page( 'cart' ) ) {
        WC()->cart->empty_cart();
        if( isset( $_GET['quantity'] ) ){
            $quantity = (int)$_GET['quantity'];
            $agent_id = $_GET['agent_id'];
            $uid = $_GET['uid'];
            $mac = $_GET['mac'];
            WC()->session->set('order_', json_encode(["agent_id" => $agent_id, "uid" => $uid, "mac" => $mac]));
            set_transient("user".$uid, json_encode($_GET));
            WC()->cart->add_to_cart( 59, $quantity );
            wp_safe_redirect( wc_get_checkout_url() );
            exit();
        }
    }
}


add_action( 'wp_head', 'misha_custom_css_on_checkout' );
function misha_custom_css_on_checkout(){
    if( is_checkout() ){
        ?>
        <style>
            #shipping-fields {
                display: none;
            }

            #billing-fields {
                display: none;
            }

            #contact-fields {
                display: none;
            }

            #shipping-option {
                display:none;
            }

            #order-notes {
                display:none;
            }

            .wp-block-woocommerce-checkout-terms-block {
                display:none;
            }

            header {
                display:none;
            }

            footer {
                display:none;
            }

            .storefront-breadcrumb {
                display:none;
            }

            .wp-block-woocommerce-checkout-order-summary-totals-block {
                display: none;
            }

            .wp-block-woocommerce-checkout-order-summary-cart-items-block {
                display: none;
            }

            #customer_details {
                display:none;
            }

            #order_review_heading, #order_review {
                width: 100%;
                margin-top:20px;
            }

            .woocommerce-terms-and-conditions-wrapper {
                display:none;
            }

            .place-order > p {
                display:none;
            }

            .woocommerce-checkout-review-order-table > tbody, .woocommerce-checkout-review-order-table > thead {
                display: none;
            }

            .woocommerce-checkout-review-order-table > tfoot tr.cart-subtotal {
                display: none;
            }

            .woocommerce-checkout > h3 {
                display: none;
            }


        </style>
        <?php
    }
}

function connect_to_remote_db_and_return_connection()
{
    $mysqli = new mysqli(remote_host, remote_user, remote_password, remote_dbname, remote_port);

    if ($mysqli->connect_error) {
        die("Connection failed: " . $mysqli->connect_error);
    }

    return $mysqli;
}


function update_meta_value_by_order_id_and_meta_key($order_id, $meta_key, $meta_value)
{
    global $wpdb;
    $table_name = $wpdb->prefix . 'wc_orders_meta';
    $query = "INSERT INTO $table_name (order_id, meta_key, meta_value) VALUES ($order_id, '".$meta_key."', '$meta_value')";
    $wpdb->query($query);
}

add_action('woocommerce_checkout_order_processed', 'save_custom_field_to_order_meta', 10, 2);
function save_custom_field_to_order_meta($order_id) {
    if ( WC()->session->get('order_') ) {
        $order_ = WC()->session->get('order_');
        $order_ = json_decode($order_, true);
        update_meta_value_by_order_id_and_meta_key($order_id, "_wc_acof_2", $order_["agent_id"]);
        update_meta_value_by_order_id_and_meta_key($order_id, "_wc_acof_3", $order_["uid"]);
        update_meta_value_by_order_id_and_meta_key($order_id, "_wc_acof_5", $order_["mac"]);
    }
}

function add_to_user_balance_on_order_completion( $order_id ) {

    $order = wc_get_order( $order_id );
    $agent_id = $order->get_meta('_wc_acof_2');
    $uid = $order->get_meta('_wc_acof_3');
    
    $order_details = json_decode(get_transient("user".$uid), true);
    $mac = $order_details["mac"];
   // $remote_order_id = $order->get_meta('_wc_acof_4');
    $total = $order->get_total();

    $secret_token = "pay_sharewifi_secret_token";
    
    $request_data = json_encode([
        "uid" => $uid,
        "spread_uid" => $agent_id,
        "cartNum" => $total,
        "token" => hash_hmac('sha256', time(), $secret_token)
    ]);
    
    
    $curl = curl_init();

    $url = api_remote_host.'/api/create_order_gcash';
    

curl_setopt_array($curl, array(
  CURLOPT_URL => $url,
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_ENCODING => '',
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_TIMEOUT => 0,
  CURLOPT_FOLLOWLOCATION => true,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => 'POST',
  CURLOPT_POSTFIELDS => $request_data,
  CURLOPT_HTTPHEADER => array(
    'Content-Type: application/json'
  ),
));

$response = curl_exec($curl);
curl_close($curl);

    $connection = connect_to_remote_db_and_return_connection();
    $stmt = $connection->prepare("SELECT balance FROM eb_user_agent_balance WHERE agent_id = ? AND user_id = ?");
    $stmt->bind_param('ii', $agent_id, $uid);
    $stmt->execute();
    $stmt->bind_result($balance);
    $stmt->fetch();
    $stmt->close();
    
    if ($balance == null) {
       $insert_stmt = $connection->prepare("INSERT INTO eb_user_agent_balance (agent_id, user_id, balance) VALUES (?, ?, ?)");
       $initial_balance = 0; 
       $insert_stmt->bind_param('iii', $agent_id, $uid, $initial_balance);
       $insert_stmt->execute();
       $insert_stmt->close();
    }
    
    $stmt = $connection->prepare("SELECT balance FROM eb_user_agent_balance WHERE agent_id = ? AND user_id = ?");
    $stmt->bind_param('ii', $agent_id, $uid);
    $stmt->execute();
    $stmt->bind_result($balance);
    $stmt->fetch();
    $stmt->close();
    
    $updated = $balance + $total;
    $stmt2 = $connection->prepare("UPDATE eb_user_agent_balance SET balance = ? WHERE agent_id = ? AND user_id = ?");
    $stmt2->bind_param('iii', $updated, $agent_id, $uid);
    $stmt2->execute();
    $stmt2->close();
    
    
    $type = 2;
    $action = 1;
    $no = time();
    $title = 'GCash';
    $last_time_price = 0;
    $create_time = date('Y-m-d H:i:s');
    $stmt3 = $connection->prepare("INSERT INTO eb_user_bill_record (agent_id, uid, equipment_mac, type, action, no, title, price, last_time_price, balance, create_time) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
    $stmt3->bind_param('iisiissiiii', $agent_id, $uid, $mac, $type, $action, $no, $title, $total, $last_time_price, $total, $create_time);
    if($stmt3->error){
        echo $stmt3->error;
        die();
    }
    $stmt3->execute();
    $stmt3->close();
    
    
    //$inserted_id = create_remote_order_for_the_user($connection, $agent_id, $user_id, $mac, $added, $updated);
    $connection->close();
    
    update_meta_value_by_order_id_and_meta_key($order_id, "_wc_acof_4", $connection->insert_id);

}
add_action( 'woocommerce_payment_complete', 'add_to_user_balance_on_order_completion' );


function create_remote_order_for_the_user($connection, $agent_id, $uid, $mac, $price, $total)
{
    $type = 2;
    $action = 1;
    $no = time();
    $title = 'GCash';
    $last_time_price = 0;
    $create_time = date('Y-m-d H:i:s');
    $stmt = $connection->prepare("INSERT INTO eb_user_bill_record (agent_id, uid, equipment_mac, type, action, no, title, price, last_time_price, balance, create_time) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
    $stmt->bind_param('iisiissiiii', $agent_id, $uid, $mac, $type, $action, $no, $title, $price, $last_time_price, $total, $create_time);
    if($stmt->error){
        echo $stmt->error;
        die();
    }
    $stmt->execute();
    $stmt->close();
    return $connection->insert_id;
}

add_filter( 'manage_woocommerce_page_wc-orders_columns', 'add_wc_order_list_custom_column' );
function add_wc_order_list_custom_column( $columns ) {
    $reordered_columns = array();
    foreach( $columns as $key => $column){
        $reordered_columns[$key] = $column;

        if( $key ===  'order_status' ){
            $reordered_columns['uid'] = __( 'UID','storefront');
            $reordered_columns['agent_id'] = __( 'Agent ID','storefront');
            $reordered_columns['mac'] = __( 'MAC','storefront');
            $reordered_columns['order_id'] = __( 'Order ID','storefront');
        }
    }
    return $reordered_columns;
}

add_action('manage_woocommerce_page_wc-orders_custom_column', 'display_wc_order_list_custom_column_content', 10, 2);
function display_wc_order_list_custom_column_content( $column, $order ){
    switch ( $column )
    {
        case 'uid' :
            $value = $order->get_meta('_wc_acof_2');
            if ( ! empty($value) ) {

                echo $value;

            }else{

                echo '<small>(<em>no value</em>)</small>';
            }
            break;

        case 'agent_id' :

            $value = $order->get_meta('_wc_acof_3');
            if ( ! empty($value) ) {
                echo $value;
            }else {
                echo '<small>(<em>no value</em>)</small>';
            }
            break;

        case 'order_id':

            $value = $order->get_meta('_wc_acof_4');
            if ( ! empty($value) ) {
                echo $value;
            }else {
                echo '<small>(<em>no value</em>)</small>';
            }
            break;

        case 'mac':

            $value = $order->get_meta('_wc_acof_5');
            if ( ! empty($value) ) {
                echo $value;
            }else {
                echo '<small>(<em>no value</em>)</small>';
            }
            break;

    }
}


add_action( 'woocommerce_thankyou', 'custom_redirect_after_purchase' );

function custom_redirect_after_purchase( $order_id ) {
    
    // Make sure we have an order ID
    if ( ! $order_id ) {
        return;
    }

    $order = wc_get_order( $order_id );

    if($order->get_status() == 'processing'){
        $order->update_status( "completed" );
    }
    
    $uid = $order->get_meta('_wc_acof_3');
    
    $url_arrays = json_decode(get_transient("user".$uid), true);
    
    $build_array = [
          'gw_mac' => $url_arrays['gw_mac'],
          'c_mac' => $url_arrays['mac'], 
          'c_ip' => $url_arrays['c_ip'],
          'gw_ip' => $url_arrays['gw_ip']
        ];
        
    $root_url = fontend_root_domain."/pages/coinMachine/coinMachine?";
    
    $redirect_url = $root_url.http_build_query($build_array);

    header( "Location:$redirect_url" );
    exit;
}
